<?php

class UserController extends Controller
{

	/**
	 * 个人资料
	 */
	public function actionProfile()
	{
		$model = Yii::app()->user->getModel();
		$model->setScenario('profile');
		if (Yii::app()->request->isPostRequest) {
			$password = $model->password;
			$model->attributes = $_POST['User'];
			if ($password === $model->password && empty($model->password2)) {
				$model->password2 = $password;
			}
			if ($model->username === 'demo' && $password !== $model->password) {
				$model->addError('password', 'demo 用户不允许改密码');
			} elseif ($model->validate()) {
				try {
					$model->save(false);
					Yii::app()->user->setFlash('success', '保存成功');
				} catch (CDbException $e) {
					Yii::app()->user->setFlash('error', $e->getMessage());
				}
			}
		}
		$this->render('profile', array('model' => $model));
	}

	/**
	 * 用户列表 (管理员专用)
	 */
	public function actionIndex()
	{
		$dataProvider = new CActiveDataProvider('User');
		$this->render('index', array('gridDataProvider' => $dataProvider));
	}

	/**
	 * 创建用户 (管理员专用)
	 */
	public function actionCreate($id = null)
	{
		$model = $this->loadModel($id);
		if (Yii::app()->request->isPostRequest) {
			$model->attributes = Yii::app()->request->getPost('User', array());
			if ($model->validate()) {
				$model->access_item = Yii::app()->request->getPost('accessItem', array());
				try {
					$model->save(false);
					Yii::app()->user->setFlash('success', '保存成功');
					$this->redirect(array('user/update', 'id' => $model->id));
				} catch (CDbException $e) {
					Yii::app()->user->setFlash('error', $e->getMessage());
				}
			}
		}
		$projects = array();
		foreach (Yii::app()->pf->getAll() as $tmp) {
			$projects[] = $tmp['name'];
		}
		$this->render('create', array(
			'model' => $model,
			'accessList' => Yii::app()->params['accessList'],
			'projects' => $projects,
		));
	}

	/**
	 * 编辑用户 (管理员专用)
	 */
	public function actionUpdate($id)
	{
		$this->actionCreate($id);
	}

	/**
	 * 删除用户 (管理员专用)
	 */
	public function actionDelete($id)
	{
		if (Yii::app()->request->isAjaxRequest) {
			$model = $this->loadModel($id);
			if (!$model->getIsAdmin()) {
				$model->delete();
			} else {
				throw new CHttpException(403, '不可以删除管理员');
			}
		}
	}

	/**
	 * @param mixed $id
	 * @return User
	 * @throws CHttpException
	 */
	private function loadModel($id)
	{
		if ($id === null) {
			$model = new User();
		} elseif (($model = User::model()->findByPk($id)) === null) {
			throw new CHttpException(404, '不存在的用户 Id#' . $id);
		}
		return $model;
	}
}
